<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Coach extends Model
{
    const TYPE_PRIVATE_COACH = 1; // 私教
    const TYPE_GROUP_COACH = 2; // 团课教练

    protected $fillable = [
        'tenant_id',
        'user_id',
        'type',
        'realname',
        'phone',
        'gender',
        'cover_url',
        'album',
        'price',
        'sale_num',
        'brief_intro',
        'expert',
        'is_enable',
        'qualification',
        'content',
        'sort',
    ];

    public function getExpertAttribute($value)
    {
        return explode(',', $value);
    }

    public function setExpertAttribute($value)
    {
        $this->attributes['expert'] = implode(',', $value);
    }

    public function getAlbumAttribute($value)
    {
        return $value ? json_decode($value, true) : [];
    }

    public function setAlbumAttribute($value)
    {
        $this->attributes['album'] = $value ? json_encode($value) : '';
    }

    public function coachOrders()
    {
        return $this->hasMany(CoachOrder::class);
    }

    public function orderSum($date_type = 'month')
    {
        $query = $this->coachOrders()->where('is_paid', true);
        switch ($date_type) {
            case 'day':
                $query->whereDay('paid_time', '=', date('d'));
                break;
            case 'month':
                $query->whereMonth('paid_time', '=', date('m'));
                break;
            case 'year':
                $query->whereYear('paid_time', '=', date('Y'));
                break;
        }
        return $query->sum('total_fee');
    }

    public static function getSelectOptions($type)
    {
        $query = self::query()->select(['id', 'realname AS text']);
        if ($type) {
            $query->where('type', $type);
        }
        $lists = $query->get();
        $options = [];
        foreach ($lists as $item) {
            $options[$item->id] = $item['text'];
        }
        return $options;
    }

    public static function getTagsSelectOptions()
    {
        return ['减脂' => '减脂', '增肌' => '增肌', '体能训练' => '体能训练', '力量训练' => '力量训练'];
    }

}
